package com.cskaoyan.config.timer;

import com.cskaoyan.bean.CouponUser;
import com.cskaoyan.bean.CouponUserExample;
import com.cskaoyan.mapper.CouponUserMapper;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 定时查询改变数据库用户优惠卷状态，查看是否过期
 */

public class UpdateUserCouponStatusTask extends QuartzJobBean {

    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //查询出所有过期的优惠卷
        CouponUserExample example = new CouponUserExample();
        CouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false).andEndTimeLessThan(new Date()).andStatusEqualTo(0);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(example);
        //如果不为null,则进行以下
        if (couponUsers != null && couponUsers.size() > 0) {
            //遍历改变优惠卷状态
            //记录id
            List<Integer> list = new ArrayList<>();
            for (CouponUser couponUser : couponUsers) {
                System.out.println(couponUser);
                list.add(couponUser.getId());
            }
            //再次创建条件，一次性改变效率更高
            CouponUserExample updateExample = new CouponUserExample();
            CouponUserExample.Criteria updateCriteria = updateExample.createCriteria();
            updateCriteria.andIdIn(list);
            CouponUser couponUser = new CouponUser();
            couponUser.setStatus(2);
            couponUser.setUpdateTime(new Date());
            //执行
            couponUserMapper.updateByExampleSelective(couponUser, updateExample);
        }
    }
}

